import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common import *


class Base:
    """
    基础封装,封装了selenium基础方法,提供page包下类继承
    """

    def __init__(self, browser):
        # 打开浏览器,设置driver
        if browser == 'chrome':
            self.driver = webdriver.Chrome()
        elif browser == 'firefox':
            self.driver = webdriver.Firefox()
        elif browser == 'edge':
            self.driver = webdriver.Edge()
        else:
            print('不支持该浏览器')
            self.driver = None

    def get(self, url):
        # 请求需求网址
        try:
            self.driver.get(url)
        except Exception:
            print('输入地址不正确')

    def find_element(self, locator):
        try:
            return self.driver.find_element(*locator)
        except Exception:
            print('元素定位不正确')

    def click(self, locator):
        # 元素点击操作
        element = self.find_element(locator)
        if element is not None:
            element.click()
        else:
            print('定位元素不正确')

    def get_attribute(self, locator, value):
        element = self.find_element(locator)
        attribute = element.get_attribute(value)
        if attribute is not None:
            print(element.get_attribute(value))
        else:
            print('该属性不存在')

    def back(self):
        # 浏览器回退
        self.driver.back()

    def forward(self):
        # 浏览器后退
        self.driver.forward()

    def refresh(self):
        # 浏览器刷新
        self.driver.refresh()

    def quit(self, seconds=0):
        # 退出浏览器
        time.sleep(seconds)
        self.driver.quit()


if __name__ == '__main__':
    base = Base('chrome')
    base.get('https://www.baidu.com')
    base.find_element((By.ID, 'kw'))
    base.click((By.ID, 'kw'))
    base.get_attribute((By.ID, 'kw'), 'class')
    base.back()
    time.sleep(3)
    base.forward()
    base.refresh()
